use std::mem::size_of;
use std::num::Wrapping;

pub trait ToPrimitive {
  #[inline]
  fn to_isize(&self) -> Option<isize> {
    self.to_i64().as_ref().and_then(ToPrimitive::to_isize)
  }

  #[inline]
  fn to_i8(&self) -> Option<i8> {
    self.to_i64().as_ref().and_then(ToPrimitive::to_i8)
  }

  #[inline]
  fn to_i16(&self) -> Option<i16> {
    self.to_i64().as_ref().and_then(ToPrimitive::to_i16)
  }

  #[inline]
  fn to_i32(&self) -> Option<i32> {
    self.to_i64().as_ref().and_then(ToPrimitive::to_i32)
  }

  fn to_i64(&self) -> Option<i64>;

  #[inline]
  fn to_i128(&self) -> Option<i128> {
    self.to_i64().map(From::from)
  }

  #[inline]
  fn to_usize(&self) -> Option<usize> {
    self.to_u64().as_ref().and_then(ToPrimitive::to_usize)
  }

  #[inline]
  fn to_u8(&self) -> Option<u8> {
    self.to_u64().as_ref().and_then(ToPrimitive::to_u8)
  }

  #[inline]
  fn to_u16(&self) -> Option<u16> {
    self.to_u64().as_ref().and_then(ToPrimitive::to_u16)
  }

  #[inline]
  fn to_u32(&self) -> Option<u32> {
    self.to_u64().as_ref().and_then(ToPrimitive::to_u32)
  }

  fn to_u64(&self) -> Option<u64>;

  #[inline]
  fn to_u128(&self) -> Option<u128> {
    self.to_u64().map(From::from)
  }

  #[inline]
  fn to_f32(&self) -> Option<f32> {
    self.to_f64().as_ref().and_then(ToPrimitive::to_f32)
  }

  #[inline]
  fn to_f64(&self) -> Option<f64> {
    match self.to_i64() {
      Some(i) => i.to_f64(),
      None => self.to_u64().as_ref().and_then(ToPrimitive::to_f64),
    }
  }
}

macro_rules! impl_to_primitive_int_to_int {
    ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$(
        #[inline]
        fn $method(&self) -> Option<$DstT> {
            let min = $DstT::MIN as $SrcT;
            let max = $DstT::MAX as $SrcT;
            if size_of::<$SrcT>() <= size_of::<$DstT>() || (min <= *self && *self <= max) {
                Some(*self as $DstT)
            } else {
                None
            }
        }
    )*}
}

macro_rules! impl_to_primitive_int_to_uint {
    ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$(
        #[inline]
        fn $method(&self) -> Option<$DstT> {
            let max = $DstT::MAX as $SrcT;
            if 0 <= *self && (size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max) {
                Some(*self as $DstT)
            } else {
                None
            }
        }
    )*}
}

macro_rules! impl_to_primitive_int {
  ($T:ident) => {
    impl ToPrimitive for $T {
      impl_to_primitive_int_to_int! { $T:
          fn to_isize -> isize;
          fn to_i8 -> i8;
          fn to_i16 -> i16;
          fn to_i32 -> i32;
          fn to_i64 -> i64;
          fn to_i128 -> i128;
      }

      impl_to_primitive_int_to_uint! { $T:
          fn to_usize -> usize;
          fn to_u8 -> u8;
          fn to_u16 -> u16;
          fn to_u32 -> u32;
          fn to_u64 -> u64;
          fn to_u128 -> u128;
      }

      #[inline]
      fn to_f32(&self) -> Option<f32> {
        Some(*self as f32)
      }
      #[inline]
      fn to_f64(&self) -> Option<f64> {
        Some(*self as f64)
      }
    }
  };
}

impl_to_primitive_int!(isize);
impl_to_primitive_int!(i8);
impl_to_primitive_int!(i16);
impl_to_primitive_int!(i32);
impl_to_primitive_int!(i64);
impl_to_primitive_int!(i128);

macro_rules! impl_to_primitive_uint_to_int {
    ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$(
        #[inline]
        fn $method(&self) -> Option<$DstT> {
            let max = $DstT::MAX as $SrcT;
            if size_of::<$SrcT>() < size_of::<$DstT>() || *self <= max {
                Some(*self as $DstT)
            } else {
                None
            }
        }
    )*}
}

macro_rules! impl_to_primitive_uint_to_uint {
    ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$(
        #[inline]
        fn $method(&self) -> Option<$DstT> {
            let max = $DstT::MAX as $SrcT;
            if size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max {
                Some(*self as $DstT)
            } else {
                None
            }
        }
    )*}
}

macro_rules! impl_to_primitive_uint {
  ($T:ident) => {
    impl ToPrimitive for $T {
      impl_to_primitive_uint_to_int! { $T:
          fn to_isize -> isize;
          fn to_i8 -> i8;
          fn to_i16 -> i16;
          fn to_i32 -> i32;
          fn to_i64 -> i64;
          fn to_i128 -> i128;
      }

      impl_to_primitive_uint_to_uint! { $T:
          fn to_usize -> usize;
          fn to_u8 -> u8;
          fn to_u16 -> u16;
          fn to_u32 -> u32;
          fn to_u64 -> u64;
          fn to_u128 -> u128;
      }

      #[inline]
      fn to_f32(&self) -> Option<f32> {
        Some(*self as f32)
      }
      #[inline]
      fn to_f64(&self) -> Option<f64> {
        Some(*self as f64)
      }
    }
  };
}

impl_to_primitive_uint!(usize);
impl_to_primitive_uint!(u8);
impl_to_primitive_uint!(u16);
impl_to_primitive_uint!(u32);
impl_to_primitive_uint!(u64);
impl_to_primitive_uint!(u128);

macro_rules! impl_to_primitive_float_to_float {
    ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$(
        #[inline]
        fn $method(&self) -> Option<$DstT> {
            // We can safely cast all values, whether NaN, +-inf, or finite.
            // Finite values that are reducing size may saturate to +-inf.
            Some(*self as $DstT)
        }
    )*}
}

macro_rules! float_to_int_unchecked {
  ($float:expr => $int:ty) => {
    $float as $int
  };
}

macro_rules! impl_to_primitive_float_to_signed_int {
    ($f:ident : $( fn $method:ident -> $i:ident ; )*) => {$(
        #[inline]
        fn $method(&self) -> Option<$i> {
            if size_of::<$f>() > size_of::<$i>() {
                const MIN_M1: $f = $i::MIN as $f - 1.0;
                const MAX_P1: $f = $i::MAX as $f + 1.0;
                if *self > MIN_M1 && *self < MAX_P1 {
                    return Some(float_to_int_unchecked!(*self => $i));
                }
            } else {
                const MIN: $f = $i::MIN as $f;
                const MAX_P1: $f = $i::MAX as $f;
                if *self >= MIN && *self < MAX_P1 {
                    return Some(float_to_int_unchecked!(*self => $i));
                }
            }
            None
        }
    )*}
}

macro_rules! impl_to_primitive_float_to_unsigned_int {
    ($f:ident : $( fn $method:ident -> $u:ident; )*) => {$(
        #[inline]
        fn $method(&self) -> Option<$u> {
            if size_of::<$f>() > size_of::<$u>() {
                const MAX_P1: $f = $u::MAX as $f + 1.0;
                if *self > -1.0 && *self < MAX_P1 {
                    return Some(float_to_int_unchecked!(*self => $u));
                }
            } else {
                const MAX_P1: $f = $u::MAX as $f;
                if *self > -1.0 && *self < MAX_P1 {
                    return Some(float_to_int_unchecked!(*self => $u));
                }
            }
            None
        }
    )*}
}

macro_rules! impl_to_primitive_float {
  ($T:ident) => {
    impl ToPrimitive for $T {
      impl_to_primitive_float_to_signed_int! { $T:
          fn to_isize -> isize;
          fn to_i8 -> i8;
          fn to_i16 -> i16;
          fn to_i32 -> i32;
          fn to_i64 -> i64;
          fn to_i128 -> i128;
      }

      impl_to_primitive_float_to_unsigned_int! { $T:
          fn to_usize -> usize;
          fn to_u8 -> u8;
          fn to_u16 -> u16;
          fn to_u32 -> u32;
          fn to_u64 -> u64;
          fn to_u128 -> u128;
      }

      impl_to_primitive_float_to_float! { $T:
          fn to_f32 -> f32;
          fn to_f64 -> f64;
      }
    }
  };
}

impl_to_primitive_float!(f32);
impl_to_primitive_float!(f64);

pub trait FromPrimitive: Sized {
  #[inline]
  fn from_isize(n: isize) -> Option<Self> {
    n.to_i64().and_then(FromPrimitive::from_i64)
  }

  #[inline]
  fn from_i8(n: i8) -> Option<Self> {
    FromPrimitive::from_i64(From::from(n))
  }

  #[inline]
  fn from_i16(n: i16) -> Option<Self> {
    FromPrimitive::from_i64(From::from(n))
  }

  #[inline]
  fn from_i32(n: i32) -> Option<Self> {
    FromPrimitive::from_i64(From::from(n))
  }

  fn from_i64(n: i64) -> Option<Self>;

  #[inline]
  fn from_i128(n: i128) -> Option<Self> {
    n.to_i64().and_then(FromPrimitive::from_i64)
  }

  #[inline]
  fn from_usize(n: usize) -> Option<Self> {
    n.to_u64().and_then(FromPrimitive::from_u64)
  }

  #[inline]
  fn from_u8(n: u8) -> Option<Self> {
    FromPrimitive::from_u64(From::from(n))
  }

  #[inline]
  fn from_u16(n: u16) -> Option<Self> {
    FromPrimitive::from_u64(From::from(n))
  }

  #[inline]
  fn from_u32(n: u32) -> Option<Self> {
    FromPrimitive::from_u64(From::from(n))
  }

  fn from_u64(n: u64) -> Option<Self>;

  #[inline]
  fn from_u128(n: u128) -> Option<Self> {
    n.to_u64().and_then(FromPrimitive::from_u64)
  }

  #[inline]
  fn from_f32(n: f32) -> Option<Self> {
    FromPrimitive::from_f64(From::from(n))
  }

  #[inline]
  fn from_f64(n: f64) -> Option<Self> {
    match n.to_i64() {
      Some(i) => FromPrimitive::from_i64(i),
      None => n.to_u64().and_then(FromPrimitive::from_u64),
    }
  }
}

macro_rules! impl_from_primitive {
  ($T:ty, $to_ty:ident) => {
    #[allow(deprecated)]
    impl FromPrimitive for $T {
      #[inline]
      fn from_isize(n: isize) -> Option<$T> {
        n.$to_ty()
      }
      #[inline]
      fn from_i8(n: i8) -> Option<$T> {
        n.$to_ty()
      }
      #[inline]
      fn from_i16(n: i16) -> Option<$T> {
        n.$to_ty()
      }
      #[inline]
      fn from_i32(n: i32) -> Option<$T> {
        n.$to_ty()
      }
      #[inline]
      fn from_i64(n: i64) -> Option<$T> {
        n.$to_ty()
      }
      #[inline]
      fn from_i128(n: i128) -> Option<$T> {
        n.$to_ty()
      }

      #[inline]
      fn from_usize(n: usize) -> Option<$T> {
        n.$to_ty()
      }
      #[inline]
      fn from_u8(n: u8) -> Option<$T> {
        n.$to_ty()
      }
      #[inline]
      fn from_u16(n: u16) -> Option<$T> {
        n.$to_ty()
      }
      #[inline]
      fn from_u32(n: u32) -> Option<$T> {
        n.$to_ty()
      }
      #[inline]
      fn from_u64(n: u64) -> Option<$T> {
        n.$to_ty()
      }
      #[inline]
      fn from_u128(n: u128) -> Option<$T> {
        n.$to_ty()
      }

      #[inline]
      fn from_f32(n: f32) -> Option<$T> {
        n.$to_ty()
      }
      #[inline]
      fn from_f64(n: f64) -> Option<$T> {
        n.$to_ty()
      }
    }
  };
}

impl_from_primitive!(isize, to_isize);
impl_from_primitive!(i8, to_i8);
impl_from_primitive!(i16, to_i16);
impl_from_primitive!(i32, to_i32);
impl_from_primitive!(i64, to_i64);
impl_from_primitive!(i128, to_i128);
impl_from_primitive!(usize, to_usize);
impl_from_primitive!(u8, to_u8);
impl_from_primitive!(u16, to_u16);
impl_from_primitive!(u32, to_u32);
impl_from_primitive!(u64, to_u64);
impl_from_primitive!(u128, to_u128);
impl_from_primitive!(f32, to_f32);
impl_from_primitive!(f64, to_f64);

macro_rules! impl_to_primitive_wrapping {
    ($( fn $method:ident -> $i:ident ; )*) => {$(
        #[inline]
        fn $method(&self) -> Option<$i> {
            (self.0).$method()
        }
    )*}
}

impl<T: ToPrimitive> ToPrimitive for Wrapping<T> {
  impl_to_primitive_wrapping! {
      fn to_isize -> isize;
      fn to_i8 -> i8;
      fn to_i16 -> i16;
      fn to_i32 -> i32;
      fn to_i64 -> i64;
      fn to_i128 -> i128;

      fn to_usize -> usize;
      fn to_u8 -> u8;
      fn to_u16 -> u16;
      fn to_u32 -> u32;
      fn to_u64 -> u64;
      fn to_u128 -> u128;

      fn to_f32 -> f32;
      fn to_f64 -> f64;
  }
}

macro_rules! impl_from_primitive_wrapping {
    ($( fn $method:ident ( $i:ident ); )*) => {$(
        #[inline]
        fn $method(n: $i) -> Option<Self> {
            T::$method(n).map(Wrapping)
        }
    )*}
}

impl<T: FromPrimitive> FromPrimitive for Wrapping<T> {
  impl_from_primitive_wrapping! {
      fn from_isize(isize);
      fn from_i8(i8);
      fn from_i16(i16);
      fn from_i32(i32);
      fn from_i64(i64);
      fn from_i128(i128);

      fn from_usize(usize);
      fn from_u8(u8);
      fn from_u16(u16);
      fn from_u32(u32);
      fn from_u64(u64);
      fn from_u128(u128);

      fn from_f32(f32);
      fn from_f64(f64);
  }
}
#[allow(dead_code)]
#[inline]
pub fn cast<T: NumCast, U: NumCast>(n: T) -> Option<U> {
  NumCast::from(n)
}

pub trait NumCast: Sized + ToPrimitive {
  fn from<T: ToPrimitive>(n: T) -> Option<Self>;
}

macro_rules! impl_num_cast {
  ($T:ty, $conv:ident) => {
    impl NumCast for $T {
      #[inline]
      #[allow(deprecated)]
      fn from<N: ToPrimitive>(n: N) -> Option<$T> {
        n.$conv()
      }
    }
  };
}

impl_num_cast!(u8, to_u8);
impl_num_cast!(u16, to_u16);
impl_num_cast!(u32, to_u32);
impl_num_cast!(u64, to_u64);
impl_num_cast!(u128, to_u128);
impl_num_cast!(usize, to_usize);
impl_num_cast!(i8, to_i8);
impl_num_cast!(i16, to_i16);
impl_num_cast!(i32, to_i32);
impl_num_cast!(i64, to_i64);
impl_num_cast!(i128, to_i128);
impl_num_cast!(isize, to_isize);
impl_num_cast!(f32, to_f32);
impl_num_cast!(f64, to_f64);

impl<T: NumCast> NumCast for Wrapping<T> {
  fn from<U: ToPrimitive>(n: U) -> Option<Self> {
    T::from(n).map(Wrapping)
  }
}

pub trait AsPrimitive<T>: 'static + Copy
where
  T: 'static + Copy,
{
  fn as_(self) -> T;
}

macro_rules! impl_as_primitive {
    (@ $T: ty =>  impl $U: ty ) => {
        impl AsPrimitive<$U> for $T {
            #[inline] fn as_(self) -> $U { self as $U }
        }
    };
    (@ $T: ty => { $( $U: ty ),* } ) => {$(
        impl_as_primitive!(@ $T => impl $U);
    )*};
    ($T: ty => { $( $U: ty ),* } ) => {
        impl_as_primitive!(@ $T => { $( $U ),* });
        impl_as_primitive!(@ $T => { u8, u16, u32, u64, usize });
        impl_as_primitive!(@ $T =>  impl u128);
        impl_as_primitive!(@ $T => { i8, i16, i32, i64, isize });
        impl_as_primitive!(@ $T =>  impl i128);
    };
}

impl_as_primitive!(u8 => { char, f32, f64 });
impl_as_primitive!(i8 => { f32, f64 });
impl_as_primitive!(u16 => { f32, f64 });
impl_as_primitive!(i16 => { f32, f64 });
impl_as_primitive!(u32 => { f32, f64 });
impl_as_primitive!(i32 => { f32, f64 });
impl_as_primitive!(u64 => { f32, f64 });
impl_as_primitive!(i64 => { f32, f64 });
impl_as_primitive!(u128 => { f32, f64 });
impl_as_primitive!(i128 => { f32, f64 });
impl_as_primitive!(usize => { f32, f64 });
impl_as_primitive!(isize => { f32, f64 });
impl_as_primitive!(f32 => { f32, f64 });
impl_as_primitive!(f64 => { f32, f64 });
impl_as_primitive!(char => { char });
impl_as_primitive!(bool => {});
